<script lang="ts" setup>
import { ref, onMounted, nextTick } from 'vue'
import { ElMessage, ElTree } from 'element-plus'
import wsjzglService from '@/api/wsjzgl'
import { useRoute } from 'vue-router'
import TreeUtilDTO from '@/utils/tree'
import wjzs from '@/components/wjzs.vue'

const route = useRoute()
const wjzsRef = ref<InstanceType<typeof wjzs>>()
// 入参
const form = ref({
  gjz: '',
})

// 生命周期
onMounted(() => {
  // 查询纸质目录
  queryZzml()
})

const defaultProps = {
  children: 'children',
  label: 'mc',
  disabled: (data: any) => {
    if (data.sfzzajml === 'N' || !data.sfzzajml) {
      return true
    }
    return false
  },
}

/*
 * 查询纸质目录
 */
const queryZzml = () => {
  //
}
const treeRef = ref<InstanceType<typeof ElTree>>()

// 文字过滤
const filtersTree = () => {
  treeRef.value?.filter(form.value.gjz)
}

const treeData = ref<any[]>([])
const queryAjml = () => {
  const params = {
    ajbh: route.query.ajbh as unknown as string,
    mlmc: '',
    mlxslx: '0',
  }
  wsjzglService
    .queryAjmls(params)
    .then((res) => {
      let obj = route.query
      res.data?.forEach((item: any) => {
        if (!item.fbh) {
          item['fbh'] = obj.ajbh
        }
      })
      //处理数据
      res.data.push({
        ajbh: obj.ajbh,
        bh: obj.ajbh,
        mc: obj.ajmc,
        wjsl: 0,
      })

      let filteredData = TreeUtilDTO.getTreeData(res.data, 'bh', 'fbh')
      filteredData.forEach((item: any) => {
        if (item.children && item.children.length > 0) {
          item.children = item.children.filter((el: any) => {
            return el.mc !== '待编目材料'
          })
        }
      })

      treeData.value = filteredData

      treeData.value?.forEach((data: any) => {
        if (data.children && data.children.length > 0) {
          data.children.forEach((data1: any) => {
            data.wjsl += data1.wjsl
            if (data1.children && data1.children.length > 0) {
              data1.children.forEach((data2: any) => {
                if (data1.bh === data2.fbh && data1.mc === '正卷') {
                  data2['zfj'] = '正卷'
                }
                if (data1.bh === data2.fbh && data1.mc === '副卷') {
                  data2['zfj'] = '副卷'
                }
                if (data1.sfzzajml === 'N') {
                  data2['sfzzajml'] = 'N'
                }
              })
            }
          })
        }
      })
      if (treeData.value.length) {
        firtsNode.value = null
        // 递归选择第一个
        getFirstNode(treeData.value)
        if (firtsNode.value) {
          handleCheckNode(firtsNode.value)
        }
      }
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
}

const getFirstNode = (arr: any[]) => {
  if (firtsNode.value) return
  for (let i = 0; i < arr.length; i++) {
    if (arr[i].children && arr[i].children.length > 0) {
      getFirstNode(arr[i].children)
    } else {
      firtsNode.value = arr[i]
    }
    return
  }
}

const handleCheckNode = (node: any) => {
  treeNodeClick(node)
  nextTick(() => {
    treeRef.value!.setCurrentKey(node.bh)
  })
}

const firtsNode = ref<any>()
// 树节点点击
const treeNodeClick = (data: any) => {
  form.value.gjz = ''
}

/**
 * 树节点过滤
 */
const filtersNode = (value: any, data: any) => {
  let flag = true
  if (value) {
    if (typeof value === 'string') {
      // 文字过滤
      flag = data[defaultProps.label].indexOf(value) !== -1
    }
  }
  return flag
}

/*
 * 生成目录
 */
const url = ref()
const createZzml = () => {
  if (!checkNodes.value || checkNodes.value?.length <= 0)
    return ElMessage({ type: 'error', message: '请勾选目录' })
  const temp: any = {}
  const list = checkNodes.value.filter((el: any) => el.cj === '2')
  list.forEach((el: any) => {
    if (temp[el.fbh]) {
      temp[el.fbh].push(el)
    } else {
      temp[el.fbh] = [el]
    }
  })
  const params = {
    bmsah: route.query.bmsah as unknown as string,
    zzmlxxList: Object.keys(temp).map((key) => ({
      ajbh: temp[key][0].ajbh as string,
      mlbhList: temp[key].map((item: any) => item.bh) as string[],
      mllx: temp[key][0].zfj === '正卷' ? '1' : '2',
    })),
  }
  wsjzglService
    .createZzml(params, route.query.ajbh as string)
    .then((res: any) => {
      url.value = window.URL.createObjectURL(res)
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
}

/*
 * 打开弹框
 */
const dialogVisible = ref(false)
const openDialog = () => {
  queryAjml()
  dialogVisible.value = true
}

/*
 * 关闭弹框
 */
const closeDialog = () => {
  //
  dialogVisible.value = false
}

/*
 * 保存（成功抛出刷新）
 */
const save = () => {
  if (!checkNodes.value || checkNodes.value?.length <= 0)
    return ElMessage({ type: 'error', message: '请勾选目录' })

  const temp: any = {}
  const list = checkNodes.value.filter((el: any) => el.cj === '2')
  list.forEach((el: any) => {
    if (temp[el.fbh]) {
      temp[el.fbh].push(el)
    } else {
      temp[el.fbh] = [el]
    }
  })
  const params = {
    bmsah: route.query.bmsah as unknown as string,
    zzmlxxList: Object.keys(temp).map((key) => ({
      ajbh: temp[key][0].ajbh as string,
      mlbhList: temp[key].map((item: any) => item.bh) as string[],
      mllx: temp[key][0].zfj === '正卷' ? '1' : '2',
    })),
  }
  wsjzglService
    .saveZzml(params, route.query.ajbh as string)
    .then(() => {
      ElMessage({ type: 'success', message: '保存成功' })
      closeDialog()
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
}
const checkNodes = ref<any>([])
const checkChange = (data: any, checks: any) => {
  checkNodes.value = checks.checkedNodes
}

defineExpose({ openDialog })
</script>
<template>
  <el-dialog
    v-model="dialogVisible"
    title="纸质目录"
    width="1100px"
    :close-on-click-modal="false"
    :before-close="closeDialog"
  >
    <div class="dialog-content">
      <div class="left-tree">
        <header class="dialog-header">
          <el-input
            v-model="form.gjz"
            autosize=""
            placeholder="请输入查询关键字"
            @change="filtersTree"
          >
            <template #suffix>
              <el-icon @click="filtersTree" class="el-input__icon"><Search /></el-icon>
            </template>
          </el-input>
        </header>
        <div class="tree-box">
          <el-tree
            ref="treeRef"
            style="max-width: 600px"
            :data="treeData"
            show-checkbox
            node-key="bh"
            highlight-current
            default-expand-all
            :expand-on-click-node="false"
            :props="defaultProps"
            @node-click="treeNodeClick"
            @check="checkChange"
            :filter-node-method="filtersNode"
          >
            <template #default="{ data }">
              <span class="custom-tree-node">
                <img v-if="!data.fbh" src="@/assets/images/file-icon.png" alt="" />
                <img v-if="data.cj === '1'" src="@/assets/images/text-icon.png" alt="" />
                <img v-if="data.cj === '2'" src="@/assets/images/ellipse.png" alt="" />
                <span>&nbsp; {{ data.mc }}&nbsp;({{ data.wjsl }}) </span>
              </span>
            </template>
          </el-tree>
        </div>
        <div>
          <el-button type="success" @click="createZzml">生成目录</el-button>
        </div>
      </div>
      <div class="right-edit">
        <wjzs ref="wjzsRef" wjlx="pdf" :url="url" />
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="save">保存目录</el-button>
        <el-button @click="closeDialog">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<style lang="scss" scoped>
.dialog-content {
  width: 100%;
  height: 600px;
  display: flex;

  .left-tree {
    flex: 3;
    display: flex;
    flex-direction: column;
    .tree-box {
      flex: 1;
      flex-shrink: 0;
      overflow: auto;
    }
  }

  .right-edit {
    flex: 5;
    margin-left: 10px;
  }
}

.el-input__icon {
  cursor: pointer;
}
</style>
